package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.NcConstant;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NCException;
import com.nineclock.common.oss.OssProperties;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.dto.*;
import com.nineclock.message.enums.MessageTypeEnum;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.pojo.*;
import com.nineclock.system.mapper.*;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysCompanyService;
import com.nineclock.system.utils.HxImManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

import static com.nineclock.common.constant.MessageConstant.COMPANY_APPLY;

@Service
@Transactional
@Slf4j
public class SysCompanyServiceImpl implements SysCompanyService {
    @Autowired
    private SysCompanyMapper sysCompanyMapper;
    @Autowired
    SysCompanyUserMapper sysCompanyUserMapper;
    @Autowired
    OSS ossClient;
    @Autowired
    OssProperties ossProperties;
    @Autowired
    SmsService smsService;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysCompanyUserRoleMapper sysCompanyUserRoleMapper;

    // 查询当前用户所对应的企业列表
    @Override
    public List<SysCompanyDTO> findCompanyByUserId(long userId) {
        if (ObjectUtil.isNull(userId)) {
            throw new NCException(ResponseEnum.USER_NOT_REGISTER);
        }
      /*  LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCompany::getUserId, userId);
        List<SysCompany> companyList = sysCompanyMapper.selectList(queryWrapper);*/
        List<SysCompany> companyList = sysCompanyMapper.findCompanyByUserId(userId);
        if (companyList == null) {
            throw new NCException(ResponseEnum.USER_NOT_JOIN_COMPANY);
        }
        return BeanHelper.copyWithCollection(companyList, SysCompanyDTO.class);
    }

    // 查询公司基本信息,用于回显数据
    @Override
    public SysCompanyDTO findCompanyInfo() {
        UserInfo userInfo = CurrentUserHolder.get();
        if (userInfo == null) {
            throw new NCException(ResponseEnum.ERROR);
        }
        Long companyId = userInfo.getCompanyId();
        SysCompany sysCompany = sysCompanyMapper.selectById(companyId);
        if (sysCompany == null) {
            throw new NCException(ResponseEnum.DATA_NOT_EXISTS);
        }
        return BeanHelper.copyProperties(sysCompany, SysCompanyDTO.class);
    }

    // 上传企业logo
    @Override
    public String uploadOSS(MultipartFile file) {
        if (file == null) {
            throw new NCException(ResponseEnum.DATA_NOT_EXISTS);
        }
        // 判断是不是图片类型
        String contentType = file.getContentType();
        if (!NcConstant.ALLOWED_IMG_TYPES.contains(contentType)) {
            // 不包含正常的图片类型
            throw new NCException(ResponseEnum.INVALID_FILE_TYPE);
        }
        // 检验上传文件大小
        if (file.getSize() > NcConstant.maxFileSize) {
            // 文件太大
            throw new NCException(ResponseEnum.FILE_SIZE_EXCEED_MAX_LIMIT);
        }
        // 组装文件名/uuid/时间戳
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String suffixName = originalFilename.substring(i);
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + suffixName;
        try {
            // 上传文件至阿里云
            PutObjectResult objectResult = ossClient.putObject(ossProperties.getBucketName(), fileName, file.getInputStream());
            log.info("上传文件成功,结果为:" + fileName + objectResult.getResponse());
        } catch (IOException e) {
            e.printStackTrace();
            // 文件上传失败
            throw new NCException(ResponseEnum.FILE_UPLOAD_ERROR);
        }
        // 组装Url路径
        String imgUrl = String.format(ossProperties.getHost(), ossProperties.getBucketName()) + fileName;
        return imgUrl;
    }

    //   更新企业基本信息
    @Override
    public void updateCompanyInfo(SysCompanyDTO sysCompanyDTO) {
        // 参数检验
        String name = sysCompanyDTO.getName();
        String logo = sysCompanyDTO.getLogo();
        if (StrUtil.isEmpty(name) && StrUtil.isEmpty(logo)) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        // 判断name的唯一性
        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCompany::getName, name);
        Integer count = sysCompanyMapper.selectCount(queryWrapper);
        if (count >= 1) {
            throw new NCException(ResponseEnum.COMPANY_NAME_REPEAT);
        }
        // 进行更新企业操作
        // 取出公司Id
        Long companyId = CurrentUserHolder.get().getCompanyId();
        SysCompany sysCompany = BeanHelper.copyProperties(sysCompanyDTO, SysCompany.class);
        sysCompany.setId(companyId);
        sysCompanyMapper.updateById(sysCompany);
        // 再进行更新关联的企业员工信息
        SysCompanyUser sysCompanyUser = new SysCompanyUser();
        //sysCompanyUser.setCompanyId(companyId);
        sysCompanyUser.setCompanyName(name);
        LambdaQueryWrapper<SysCompanyUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(SysCompanyUser::getCompanyId, companyId);
        sysCompanyUserMapper.update(sysCompanyUser, userLambdaQueryWrapper);
    }

    // 获取当前登录的企业管理员
    @Override
    public SysCompanyUserDTO findCompanyUserAdmin() {
        // 获取当前登录companyId
        Long companyId = CurrentUserHolder.get().getCompanyId();
        SysCompanyUser userAdmin = sysCompanyUserMapper.findCompanyUserAdmin(companyId);
        if (userAdmin == null) {
            throw new NCException(ResponseEnum.COMPANY_ADMIN_NOT_EXISTS);
        }
        return BeanHelper.copyProperties(userAdmin, SysCompanyUserDTO.class);
    }

    // 更改管理员
    @Override
    public void updateAdmin(SysChangeMainManagerDTO sysChangeMainManagerDTO) {
        if (StrUtil.isEmpty(sysChangeMainManagerDTO.getCode()) || sysChangeMainManagerDTO.getUserId() == null) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        // 根据当前用户查询员工信息/手机号
        //SysUser sysUser = sysUserMapper.selectById(sysChangeMainManagerDTO.getUserId());
        SysCompanyUser sysCompanyUser = sysCompanyUserMapper.selectById(sysChangeMainManagerDTO.getUserId());
        if (sysCompanyUser == null) {
            throw new NCException(ResponseEnum.USER_NOT_FOUND);
        }
        Long companyId = CurrentUserHolder.get().getCompanyId();
        // 校验验证码
        Boolean result = smsService.verify(sysChangeMainManagerDTO.getCode(), "3", sysCompanyUser.getMobile());
        if (result) {
            /*  删除原管理员的数据*/
            //    获取到原管理员
            SysCompanyUser oldUserAdmin = sysCompanyUserMapper.findCompanyUserAdmin(companyId);
            // 查询当前企业系统管理员的角色ID
            LambdaQueryWrapper<SysRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(SysRole::getRoleName, "ROLE_ADMIN_SYS")
                    .eq(SysRole::getCompanyId, companyId);
            SysRole sysRole = sysRoleMapper.selectOne(roleWrapper);
            // 删除中间关联表
            LambdaQueryWrapper<SysCompanyUserRole> userRoleWrapper = new LambdaQueryWrapper<>();
            userRoleWrapper.eq(SysCompanyUserRole::getCompanyUserId, oldUserAdmin.getId())
                    .eq(SysCompanyUserRole::getCompanyId, oldUserAdmin.getCompanyId())
                    .eq(SysCompanyUserRole::getRoleId, sysRole.getId());
            sysCompanyUserRoleMapper.delete(userRoleWrapper);
            /*添加新的系统管理员*/
            SysCompanyUserRole sysCompanyUserRole = new SysCompanyUserRole();
            sysCompanyUserRole.setCompanyId(companyId);
            sysCompanyUserRole.setCompanyUserId(sysChangeMainManagerDTO.getUserId());
            sysCompanyUserRole.setRoleId(sysRole.getId());
            sysCompanyUserRoleMapper.insert(sysCompanyUserRole);
        } else {
            throw new NCException(ResponseEnum.CODE_IMAGE_ERROR);
        }
    }

    // 根据关键字查询企业列表
    @Override
    public List<SysCompanyDTO> findCompanyByKeyword(String keyword) {
        // 校验参数,如果没有传递关键字,则查询所有企业列表
        if (StrUtil.isEmpty(keyword)) {
            // 查询所有的企业列表供参考
            List<SysCompany> sysCompanyList = sysCompanyMapper.selectList(null);
            if (sysCompanyList != null) {
                return BeanHelper.copyWithCollection(sysCompanyList, SysCompanyDTO.class);
            }
        }
        // 根据关键字模糊查询
        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SysCompany::getName, keyword);
        List<SysCompany> sysCompanyList = sysCompanyMapper.selectList(queryWrapper);
        return BeanHelper.copyWithCollection(sysCompanyList, SysCompanyDTO.class);
    }

    // 加入企业申请
    @Autowired
    RocketMQTemplate rocketMQTemplate;
    @Autowired
    HxImManager hxImManager;
    @Override
    public void applyJoinCompany(SysApplyJoinCompanyUserDTO joinCompanyUserDTO) {
        if (joinCompanyUserDTO == null) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        // 更新用户基本信息
        SysUser sysUser = sysUserMapper.selectById(joinCompanyUserDTO.getUserId());
        sysUser.setUsername(joinCompanyUserDTO.getUserName());
        sysUser.setLastLoginCompanyId(joinCompanyUserDTO.getCompanyId());
        sysUserMapper.updateById(sysUser);
        // 添加当前企业员工信息
        SysCompanyUser sysCompanyUser = new SysCompanyUser();
        sysCompanyUser.setCompanyId(joinCompanyUserDTO.getCompanyId());
        sysCompanyUser.setCompanyName(joinCompanyUserDTO.getCompanyName());
        sysCompanyUser.setCreateTime(new Date());
        sysCompanyUser.setEmail(joinCompanyUserDTO.getEmail());
        sysCompanyUser.setEnable((short) 0);
        sysCompanyUser.setPost(joinCompanyUserDTO.getPost());
        sysCompanyUser.setImageUrl(joinCompanyUserDTO.getImageUrl());
        sysCompanyUser.setUserId(joinCompanyUserDTO.getUserId());
        sysCompanyUser.setUserName(joinCompanyUserDTO.getUserName());
        sysCompanyUser.setMobile(joinCompanyUserDTO.getMobile());
        sysCompanyUserMapper.insert(sysCompanyUser);
        /*----------发送审核消息----------------*/
        // 获取到当前系统管理员
        SysCompanyUser admin = sysCompanyUserMapper.findCompanyUserAdmin(joinCompanyUserDTO.getCompanyId());

        // 构建message,发送消息到MQ
        NcMessage ncMessage = new NcMessage();
        ncMessage.setApplyUserId(joinCompanyUserDTO.getUserId()); // 申请人Id
        ncMessage.setApplyUsername(joinCompanyUserDTO.getUserName()); // 申请人名字
        ncMessage.setApproveUserId(admin.getUserId()); // 谁处理的id //id
        ncMessage.setApproveUsername(admin.getUserName()); // 谁处理的名字
        ncMessage.setCompanyId(String.valueOf(joinCompanyUserDTO.getCompanyId())); // 企业ID
        ncMessage.setUseStatus(0); // 未读
        ncMessage.setContent(joinCompanyUserDTO.getUserName() + "申请加入企业,请即使审批"); //消息摘要
        ncMessage.setCreateTime(new Date()); // 当前时间
        ncMessage.setMessageType(MessageTypeEnum.COMPANY_APPLY.getType()); // 消息类型
        ncMessage.setApproveStatue(0); // 审核状态
        ncMessage.setTargets(Collections.singletonList(admin.getMobile())); // 让谁审核,审核人表示/目前是别名/手机号
        // 发送Mq
        rocketMQTemplate.convertAndSend("messagePushTopic", ncMessage);
        /*----------------注册用户到环信云,便于以后的即时通讯----------*/
        //注册用户到环信云, 用于APP端用户之间的及时通讯
        sysUser.setPassword("123456");
        sysUser.setUsername(sysUser.getMobile());
        hxImManager.registerUser2HuanXing(sysUser);
        log.info("注册用户到环信云");
    }
    // 审核加入企业
    @Override
    public void allowedJoinCompany(SysAllowedJoinCompanyUserDTO sysAllowedJoinCompanyUserDTO) {
        // 校验参数
        if (sysAllowedJoinCompanyUserDTO == null) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        // 根据条件更新员工状态
        Long companyId = CurrentUserHolder.get().getCompanyId();
        // 根据公司id以及用户Id查询员工信息
        LambdaQueryWrapper<SysCompanyUser> companyUserWrapper = new LambdaQueryWrapper<>();
        companyUserWrapper.eq(SysCompanyUser::getCompanyId, companyId);
        companyUserWrapper.eq(SysCompanyUser::getUserId, sysAllowedJoinCompanyUserDTO.getApplyUserId());
        SysCompanyUser sysCompanyUser = sysCompanyUserMapper.selectOne(companyUserWrapper);
        if (sysCompanyUser != null) {
            // 更新员工状态
            //sysCompanyUser.setEnable((short) 1);
            sysCompanyUser.setEnable(sysAllowedJoinCompanyUserDTO.getApproved()?(short)1:(short)0);
            sysCompanyUser.setRemark(sysAllowedJoinCompanyUserDTO.getRemark());
        }
        sysCompanyUserMapper.updateById(sysCompanyUser);
        // 发送消息到mq,更新状态
        rocketMQTemplate.convertAndSend("AllowedMessageUpdate", sysAllowedJoinCompanyUserDTO.getNotifyMsgId());
        // 发送消息到RocketMQ, 推送消息给该用户, 通知审核通过
        SysUser sysUser = sysUserMapper.selectById(sysAllowedJoinCompanyUserDTO.getApplyUserId());

        // 构建message,发送消息到MQ
        NcMessage ncMessage = new NcMessage();
        ncMessage.setApplyUserId(sysAllowedJoinCompanyUserDTO.getApplyUserId()); // 申请人Id
        ncMessage.setApplyUsername(sysUser.getUsername()); // 申请人名字
        ncMessage.setApproveUserId(CurrentUserHolder.get().getId()); // 谁处理的id //id
        ncMessage.setCompanyId(String.valueOf(CurrentUserHolder.get().getCompanyId())); // 企业ID
        ncMessage.setContent(sysUser.getUsername()+"已同意你的申请加入企业"); //消息摘要
        ncMessage.setCreateTime(new Date()); // 当前时间
        ncMessage.setMessageType(MessageTypeEnum.COMPANY_APPLY_PASS.getType()); // 消息类型
        ncMessage.setTargets(Collections.singletonList(sysUser.getMobile())); // 让谁审核,审核人表示/目前是别名/手机号
        // 发送Mq
        rocketMQTemplate.convertAndSend("messagePushTopic", ncMessage);
    }
}
